const { sys_dict_model:SysDictModel, sys_dict_data_model:SysDictDataModel } = require('../models');
const { Op } = require("sequelize");
const DateUtils = require('../utils/dateUtils');
const { realDelete } = require('../config/system');

const dictService = {
    /**
     * 获取所有字典数据
     * @returns {Promise<Array>} 字典数据列表
     */
    async getAllDicts() {
        let where = {
            status: 1,
            is_deleted: 0
        };
        const dicts = await SysDictModel.findAll({
            where,
            attributes: ['id', 'name', 'dict_code'],
            include: [{
                model: SysDictDataModel,
                where: { status: 1 },
                required: true,
                attributes: ['value', 'label', 'tag_type']
            }]
        });

        // 格式化返回数据结构
        return dicts.map(dict => {
            const plainDict = dict.get({ plain: true });
            return {
                name: plainDict.name,
                dictCode: plainDict.dict_code,
                //当使用include进行关联查询时，Sequelize会自动将关联模型的查询结果附加到主模型的实例上
                dictDataList: plainDict.sys_dict_data_models?.map(data => ({
                    value: data.value,
                    label: data.label,
                    tagType: data.tag_type
                })) || []
            };
        });
    },

    /**
     * 根据ID获取字典详情
     * @param {number} id - 字典ID
     * @returns {Promise<Object>} 字典详情
     */
    async getDictById(id) {
        const dictData =  await SysDictModel.findOne({
            where: {
                id,
                is_deleted: 0
            }
        });
        if (!dictData) {
            throw new Error('字典数据不存在');
        }
        return dictData;
    },

    /**
     * 分页获取字典数据
     * @param {number} pageNum - 页码
     * @param {number} pageSize - 每页数量
     * @returns {Promise<Object>} 分页数据
     */
    async getDicByPage(pageNum, pageSize, name, dictCode, status) {
        let offset = (pageNum - 1) * pageSize;
        let where = {
            is_deleted: 0,
        };
        if (name) {
            where.name = {
                [Op.like]: `%${name}%`
            }
        }
        if (dictCode) {
            where.dict_code = {
                [Op.like]: `%${dictCode}%`
            }
        }
        if (status) {
            where.status = status;
        }
        return await SysDictModel.findAndCountAll({
            where,
            // attributes: ['id', 'name', 'dict_code'],
            attributes: { exclude: ['is_deleted'] },
            order: [
                ['create_time', 'DESC']
            ],
            limit: pageSize,
            offset
        });
    },

    /**
     * 添加字典
     * @param {Object} dictData - 字典数据
     * @returns {Promise<Object>} 创建的字典数据
     */
    async addDict(dictData) {
        const { name, dictCode, status, remark } = dictData;
        const existCode = await SysDictModel.findOne({ where: { dict_code: dictCode } });
        if (existCode) {
            throw new Error("字典编码已存在");
        }
        return await SysDictModel.create({
            name,
            dictCode: dictCode,
            remark,
            status: status != undefined ? status : 1,
            isDeleted: 0,
            createTime: DateUtils.getCurrentTime(),
            updateTime: DateUtils.getCurrentTime()
        });
    },

    /**
     * 更新字典
     * @param {Object} dictData - 字典数据
     * @returns {Promise<Array>} 更新结果
     */
    async updateDict(id, dictData) {
        const existingDictData = await SysDictModel.findByPk(id);
        if (!existingDictData) {
            throw new Error('字典数据不存在');
        }
        // 如果更新了字典编码，需要校验字典类型是否存在
        if (dictData.dict_code && dictData.dict_code !== existingDictData.dict_code) {
            const dict = await SysDictModel.findOne({
                where: { dict_code: dictData.dict_code }
            });
            if (dict) {
                throw new Error('字典类型已存在');
            }
        }
        
        const result = await existingDictData.update({
            ...dictData,
            update_time: DateUtils.getCurrentTime(),
        });
        return result;
    },

    /**
     * 删除字典
     * @param {number} id - 字典ID
     * @returns {Promise<Object>} 删除结果
     */
    async deleteDict(id) {
        const dictData = await SysDictModel.findByPk(id);
        if (!dictData) {
            throw new Error('字典数据不存在');
        }
        
        if (realDelete) {
            // 真实删除
            return await dictData.destroy();
        } else {
            // 软删除
            return await dictData.update({
                is_deleted: 1,
                update_time: DateUtils.getCurrentTime(),
            });
        }
    }
};

module.exports = dictService;